package com.heima.search.service.Impl;

import com.heima.model.common.dtos.common.ResponseResult;
import com.heima.model.common.dtos.app.UserSearchDto;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.search.pojo.ApAssociateWords;
import com.heima.search.service.ApAssociateWordsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ApAssociateWordsServiceImpl implements ApAssociateWordsService {
    @Autowired
    private MongoTemplate mongoTemplate;
    /**
     * 搜索联想词使用
     * @param userSearchDto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto userSearchDto) {
        //检验参数
        if(userSearchDto.getSearchWords()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //分页检查(最多只能查询20条)
        if(userSearchDto.getPageSize()>20){
            userSearchDto.setPageSize(20);
        }
        //执行查询
        Query query = Query.query(Criteria.where("associateWords").regex(".*?\\" + userSearchDto.getSearchWords() + ".*"));
        //分页查询前20条
        query.limit(userSearchDto.getPageSize());
        List<ApAssociateWords> apAssociateWords = mongoTemplate.find(query, ApAssociateWords.class);
        return ResponseResult.okResult(apAssociateWords);
    }
}
